package org.i_plus.listener;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Application Lifecycle Listener implementation class SessionListener
 *
 */
@WebListener
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener {

	public static Map<String, String> sessionids = null;//每個上線的account:sessionid都登記在這
    
    public SessionListener() {
        sessionids = new HashMap<String , String>();
    }

    public void attributeRemoved(HttpSessionBindingEvent arg0) {
        this.removePic(arg0);//使用者登出
        this.sessionids.remove(arg0.getSession().getAttribute("account"));//登出後移除sessionid
    }

    public void attributeAdded(HttpSessionBindingEvent arg0) {
        // TODO Auto-generated method stub
    }

    public void attributeReplaced(HttpSessionBindingEvent arg0) {
        // TODO Auto-generated method stub
    }

    public void sessionCreated(HttpSessionEvent arg0) {
    }

    public void sessionDestroyed(HttpSessionEvent arg0) {
    	this.removePic(arg0);//session銷毀
    	this.sessionids.remove(arg0.getSession().getAttribute("account"));//登出後移除sessionid
    }
   
    //銷毀圖片
    private void removePic(HttpSessionEvent arg0){
    	String account = (String)arg0.getSession().getAttribute("account");
        File f = new File("userpic/"+account+".jpg");
        f.delete();
    }
	
}
